<!-- 
自定义验证码输入、密码输入使用
 
使用方法：
maxlength：输入最大长度
isPwd：是否是密码模式
@finish：回调函数
 <validcode :maxlength="4" :isPwd="false" @finish="finish"></validcode>
 -->
<template>
  <view class="code-area">
    <view class="flex-box">
      <input
        :value="val"
        type="number"
        focus="true"
        :maxlength="maxlength"
        class="hide-input"
        @input="getVal" />
      <view
        v-for="(item, index) in maxlength"
        v-bind:class="['item', { active: codeIndex == index }]">
        <view class="line"></view>
        <block v-if="isPwd && val.length >= index + 1">
          <text class="dot">.</text>
        </block>
        <block v-else> {{ val[index] || '' }}</block>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  props: {
    //最大长度 值为4或者6
    maxlength: {
      type: Number,
      default: 4
    },
    //是否是密码
    isPwd: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      codeIndex: 0, //下标
      val: '' //输入框的值
    }
  },
  methods: {
    getVal(e) {
      const { value } = e.detail
      this.val = value
      this.codeIndex = value.length
      if (value.length == Number(this.maxlength)) {
        this.$emit('finish', value)
      }
    }, //清除验证码或者密码
    clear() {
      this.codeIndex = 0
      this.val = ''
    }
  }
}
</script>

<style lang="scss">
.code-area {
  text-align: center;
  margin-top: 40rpx;
  .flex-box {
    display: flex;
    flex-wrap: wrap;
    position: relative;
    justify-content: center;
  }

  .item {
    position: relative;
    width: 66rpx;
    height: 100rpx;
    margin-right: 18rpx;
    font-size: 30rpx;
    font-weight: bold;
    color: #333333;
    line-height: 100rpx;
    box-sizing: border-box;
    border-bottom: 2rpx solid #cccccc;
  }

  .item:last-child {
    margin-right: 0;
  }

  .active {
    border-color: #ff4b4b;
  }
  .active .line {
    display: block;
  }

  .line {
    display: none;
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
    width: 2rpx;
    height: 40rpx;
    background: #ff4b4b;
    animation: twinkling 1s infinite steps(1, start);
  }

  .hide-input {
    position: absolute;
    top: 0;
    left: -100%;
    width: 200%;
    height: 100%;
    text-align: left;
    z-index: 9;
    opacity: 1;
  }

  @keyframes twinkling {
    0%,
    100% {
      opacity: 0;
    }
    50% {
      opacity: 1;
    }
  }

  .dot {
    font-size: 80rpx;
    line-height: 40rpx;
  }
}
</style>
